/******************************************************************************

  Copyright (C), 2017-2027

 ******************************************************************************
  File Name     : messagetacklefun.cpp
  Version       : 1.0
  Created       : 2024-08-19
  History       :
  1.Date        : 2024-08-19

  消息处理模块，槽都往这边放，集中处理
******************************************************************************/
#include "messagetacklefun.h"
#include <QDebug>

#define PART_UDP 45454

MessageTackleFun::MessageTackleFun():QThread()
{
    m_udpsocket = new udpsocket(PART_UDP);
    m_WebSocketClient = new WebSocketClient();

    connect(m_udpsocket , &udpsocket::retUdpMessage , this ,&MessageTackleFun::UdpMessageFun );
    start();
}

void MessageTackleFun::run()
{
    while(1)
    {
        if( msgList.count() > 0 )
        {
            pmsg msg = msgList.first();
            if( msg->message == MSG_SEND_UDP )
            {
                QJsonObject loginObject;
                loginObject["user"] = userName;
                loginObject["pass"] = passWord;
                loginObject["status"] = "wait";
                QJsonObject mainObject;
                mainObject["id"] = UDP_LOGIN_SEND;
                mainObject["login"] = loginObject;
                // 创建 JSON 文档
                QJsonDocument jsonDoc(mainObject);
                // 将 JSON 文档转换为 QByteArray
                QByteArray byteArray = jsonDoc.toJson();
                m_udpsocket->sendMessage(byteArray);
            }
            else if( msg->message == MSG_SEND_WEB )
            {


            }


            if( msg->lParam != nullptr )
            {
                delete msg->lParam;
            }
            delete msg;

            mutexList.lock();
            msgList.removeFirst();
            mutexList.unlock();

            usleep(20*1000);
        }
    }
}
void MessageTackleFun::sendMessage( pmsg msg  )
{
    mutexList.lock();
    msgList.append(msg);
    mutexList.unlock();
}
void MessageTackleFun::login(QString user , QString password )
{
    userName = user;
    passWord = password;
    pmsg msg = new _msg;
    msg->message = MSG_SEND_UDP;
    sendMessage(msg);
}
void MessageTackleFun::UdpMessageFun( void *p )
{
    pAccessMessages m_pAccessMessages = (pAccessMessages)p;
    if( !m_WebSocketClient->isConnect() )
    {
        QString urlTemplate("ws://%1:8082/http");
        QString url = urlTemplate.arg(m_pAccessMessages->sender.toString());
        qDebug()<<"url:"<<url;
        m_WebSocketClient->m_webSocket.open(QUrl(url));
    }
    if( QString::for m_pAccessMessages->datagram  )
    emit loginReasult( m_pAccessMessages->datagram );
}
